<template>
	<view>
		<!-- #ifndef MP-WEIXIN -->
		<navBar title="发布"></navBar>
		<!-- #endif -->
		<view class="formBox">
			<u--form labelPosition="top" :model="form" :rules="rules" ref="form1">
				<u-form-item label="标题 :" prop="title" :required="true" borderBottom>
					<u--input
						@focus="focusEvent"
						v-model="form.title"
						border="none"
						placeholder="请输入文章的标题"
					></u--input>
				</u-form-item>
				<u-form-item label="文章封面 :" prop="cover" labelWidth="100px" :required="true" borderBottom>
					<u-upload @afterRead="afterRead" @delete="deletePic" :fileList="fileList"></u-upload>
				</u-form-item>
				<u-form-item label="文章分类 :" prop="classifyArr" labelWidth="100px" :required="true" borderBottom>
					<u--input
						:value="value.slice(0, -1)"
						@click.native="show = true"
						placeholder="请选择文章分类(最多可选3种)"
						border="none"
						:disabled="true"
						disabledColor="transparent"
						suffixIcon="arrow-down"
						:suffixIconStyle="{ color: '#c1cbd7' }"
					></u--input>
				</u-form-item>
				<u-form-item label="文章内容 :" labelWidth="100px" :required="true" borderBottom>
					<jin-edit
						@editOk="publish"
						uploadFileUrl="https://eggblog.bluej.cn/api/imgUpload"
						:header="{ 'x-token': userInfo.token }"
					></jin-edit>
				</u-form-item>
			</u--form>
		</view>
		<u-picker
			:show="show"
			ref="uPicker"
			:columns="columns"
			keyName="classifyName"
			@confirm="confirm"
			@cancel="reelect"
			cancelText="重选"
			cancelColor="#f56c6c"
			:closeOnClickOverlay="true"
			@close="show = false"
			confirmColor="#7fa7d7"
		></u-picker>
		<helang-compress ref="helangCompress"></helang-compress>
	</view>
</template>

<script>
import { createBlog } from '@/config/api.js';
import { mapState } from 'vuex';
export default {
	name: 'publish',
	data() {
		return {
			form: {
				title: '',
				content: '',
				cover: '',
				classifyArr: []
			},
			rules: {
				title: {
					required: true,
					min: 3,
					message: '请输入3个字符以上的文章标题',
					trigger: ['blur', 'change']
				},
				cover: {
					required: true,
					message: '请上传文章封面',
					trigger: ['change']
				},
				classifyArr: {
					type: 'array',
					required: true,
					message: '请选择文章分类',
					trigger: ['change']
				}
			},
			// 上传的文件列表
			fileList: [],
			// 分类列表
			columns: [],
			// 选择后显示的分类
			value: '',
			show: false
		};
	},
	methods: {
		// 获取焦点
		focusEvent() {
			// 清除表单校验结果
			this.$refs.form1.clearValidate();
		},
		// 读取后（数组形式，支持多选图片，但是api只需传一张）
		afterRead(e) {
			console.log(e.file);
			// 调用插件的方法进行图片压缩
			this.$refs.helangCompress
				.compress({
					src: e.file.url,
					maxSize: 800,
					fileType: 'png',
					quality: 0.8,
					minSize: -1 //最小压缩尺寸，图片尺寸小于该时值不压缩，非H5平台有效。若需要忽略该设置，可设置为一个极小的值，比如负数。
				})
				.then(res => {
					// 压缩成功回调
					console.log(res);
					let lists = [].concat(res);
					lists.map(item => {
						this.fileList.push({
							item,
							status: 'uploading',
							message: '上传中'
						});
					});
					this.fileList.forEach((ele, index) => {
						uni.uploadFile({
							url: 'https://eggblog.bluej.cn/api/imgUpload',
							filePath: ele.item,
							name: 'file',
							header: {
								'x-token': this.$store.state.userInfo
							},
							success: uploadFileRes => {
								const uploadFile = JSON.parse(uploadFileRes.data);
								this.fileList.splice(index, 1, {
									status: 'success',
									url: uploadFile.data[0]
								});
								// 把处理好的图片路径保存到form表单中
								this.form.cover = uploadFile.data[0];
								console.log(this.form.cover);
							}
						});
					});
				})
				.catch(err => {
					// 压缩失败回调
					console.log(err);
				});
			// let lists = [].concat(e.file);
			// lists.map(item => {
			// 	this.fileList.push({
			// 		...item,
			// 		status: 'uploading',
			// 		message: '上传中'
			// 	});
			// });
			// this.fileList.forEach((ele, index) => {
			// 	uni.uploadFile({
			// 		url: 'https://eggblog.bluej.cn/api/imgUpload',
			// 		filePath: ele.url,
			// 		name: 'file',
			// 		header: {
			// 			'x-token': this.$store.state.userInfo
			// 		},
			// 		success: uploadFileRes => {
			// 			const uploadFile = JSON.parse(uploadFileRes.data);
			// 			this.fileList.splice(index, 1, {
			// 				status: 'success',
			// 				url: uploadFile.data[0]
			// 			});
			// 			// 把处理好的图片路径保存到form表单中
			// 			this.form.cover = uploadFile.data[0];
			// 			console.log(this.form.cover);
			// 		}
			// 	});
			// });
		},
		// 删除图片
		deletePic(e) {
			this.fileList.splice(e.index, 1);
		},
		// 确定选择分类
		confirm(e) {
			this.show = false;
			if (this.form.classifyArr.includes(e.value[0].id)) {
				uni.showToast({
					title: '存在重复分类',
					icon: 'error',
					duration: 1500
				});
				return;
			} else if (this.form.classifyArr.length >= 3) {
				uni.showToast({
					title: '最多只能选择3种分类',
					icon: 'error',
					duration: 1500
				});
				return;
			}
			// 把选择的分类显示到页面
			this.value += e.value[0].classifyName + ',';
			// 把选择的分类ID放到表单
			this.form.classifyArr.push(e.value[0].id);
		},
		// 重选分类
		reelect() {
			this.value = '';
			this.form.classifyArr = [];
		},
		// 发布
		async publish(e) {
			try {
				this.form.content = e.html;
				await this.$refs.form1.validate();
				uni.showLoading({
					title: '正在发布'
				});
				// #ifndef MP-WEIXIN
				const res = await createBlog(this.form, this.userInfo.token);
				console.log('发布成功', res);
				setTimeout(() => {
					uni.hideLoading();
					uni.showToast({
						title: '发布成功',
						success: () => {
							setTimeout(() => {
								// 此法跳转可以刷新tabbar页面
								uni.reLaunch({
									url: '/pages/index/index'
								});
							}, 1500);
						}
					});
				}, 1000);
				// #endif
				// #ifdef MP-WEIXIN
				uni.request({
					url: 'https://eggblog.bluej.cn/api/blog/create',
					method: 'POST',
					data: {
						projectId: 155,
						...this.form
					},
					header: {
						'x-token': this.userInfo.token
					},
					success: res => {
						console.log('发布成功', res);
						setTimeout(() => {
							uni.hideLoading();
							uni.showToast({
								title: '发布成功',
								success: () => {
									setTimeout(() => {
										// 此法跳转可以刷新tabbar页面
										uni.reLaunch({
											url: '/pages/index/index'
										});
									}, 1500);
								}
							});
						}, 1000);
					}
				});
				// #endif
			} catch (err) {
				uni.hideLoading();
				console.log(err);
				if (err.data) {
					uni.showToast({
						title: err.data.msg,
						icon: 'error'
					});
				}
			}
		}
	},
	computed: {
		...mapState(['classifyList', 'userInfo'])
	},
	mounted() {
		this.columns.push(this.classifyList);
	}
};
</script>

<style lang="scss" scoped>
.formBox {
	box-sizing: border-box;
	padding: 3vw 5vw 10vh;

	::v-deep .uni-input-input {
		padding: 0 5vw;
	}
	::v-deep .uni-input-placeholder {
		padding: 0 5vw;
	}
	::v-deep .u-form-item__body__right__message {
		padding: 0 5vw;
	}
	::v-deep .tool-view {
		position: fixed;
		bottom: 0;
		left: 0;
		width: 100vw;
	}
	::v-deep .u-form-item__body__right__content__slot {
		width: 90vw;
		box-sizing: border-box;
	}
	::v-deep .ql-container {
		margin: 0 auto;
	}
	::v-deep .container {
		/* #ifndef MP-WEIXIN */
		width: 100vw;
		/* #endif */
		overflow: auto;
		height: 42vh !important;
	}
}
</style>
